﻿using System;
using System.ServiceModel;
using LB.Common;
using LB.Server.Common;
using LB.Server.DAL.EntityFramework;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

namespace LB.Server.ConsoleHost
{
    internal class Program
    {
        private static readonly ApplicationLog Log = new ApplicationLog();
        private IUnityContainer ioContainer;

        private static void Main(string[] args)
        {
            var program = new Program();
            program.EntryPoint();
        }

        private void EntryPoint()
        {
            DbFiller.FillDatabaseDropCreateIfModelChanged();
            //DbFiller.FillDatabaseIfNotExist();

            ioContainer = new UnityContainer();
            ioContainer.LoadConfiguration();
            
            var isExceptionOccured = false;
            ServiceHost bookServiceHost = null;
            ServiceHost userAdministrationServiceHost = null;

            try
            {
                var bookService = ioContainer.Resolve<IBookService>();
                bookServiceHost = new ServiceHost(bookService);
                Log.WriteInfo("Book service is being started...");
                bookServiceHost.Open();
                Log.WriteInfo("Book service has been started.");
                
                userAdministrationServiceHost = new ServiceHost(ioContainer.Resolve<IUserAdministrationService>());
                Log.WriteInfo("UserAdministration service is being started...");
                userAdministrationServiceHost.Open();
                Log.WriteInfo("UserAdministration service has been started.");

                Console.WriteLine(@"Press ENTER to exit...");
                Console.ReadLine();
                Console.WriteLine(@"Service is shutting down...");
            }
            catch (Exception e)
            {
                isExceptionOccured = true;
                Log.WriteError("Global error has been occurred - {0}", e);
            }
            finally
            {
                if (bookServiceHost != null)
                {
                    bookServiceHost.Close();
                    Log.WriteInfo("Book service has been stopped.");
                }

                if (userAdministrationServiceHost != null)
                {
                    userAdministrationServiceHost.Close();
                    Log.WriteInfo("UserAdministration service has been stopped.");
                }

                if (isExceptionOccured)
                {
                    Console.WriteLine("Press enter for exit.");
                    Console.Read();
                }
            }
        }
    }
}